package com.nlx.notes.module.service.impl.user;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nlx.notes.configuer.redis.annotation.RedisLock;
import com.nlx.notes.module.bean.dto.querydb.UserQueryDbDTO;
import com.nlx.notes.module.core.consts.GlobalConst;
import com.nlx.notes.module.core.enums.error.UserCodeEnum;
import com.nlx.notes.module.entity.Users;
import com.nlx.notes.module.mapper.UsersMapper;
import com.nlx.notes.module.service.user.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nlx.notes.support.handler.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author nlx
 * @since 2024-12-15
 */
@Slf4j
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {


    @Override
    public Users findUserByCondition(UserQueryDbDTO userQueryDbDTO) {
        if(ObjectUtil.isEmpty(userQueryDbDTO)){
            return null;
        }
        return this.getBaseMapper().selectOne(Wrappers.lambdaQuery(Users.class)
                .eq(null != userQueryDbDTO.getId(),Users::getId, userQueryDbDTO.getId())
                .eq(StrUtil.isNotEmpty(userQueryDbDTO.getUserCode()),Users::getUserCode,userQueryDbDTO.getUserCode())
                .eq(StrUtil.isNotEmpty(userQueryDbDTO.getPhone()),Users::getUserPhone,userQueryDbDTO.getPhone())
                .eq(StrUtil.isNotEmpty(userQueryDbDTO.getEmail()),Users::getEmail,userQueryDbDTO.getEmail())
                .eq(Users::getDelFlag, GlobalConst.DEL_FLAG_NORMAL).last(" limit 1"));
    }

    @Override
    @RedisLock(key = " 'user_bind_phone:' + #phone")
    public boolean bindPhone(Long userId, String phone) {
        UserQueryDbDTO userQueryDbDTO = new UserQueryDbDTO();
        userQueryDbDTO.setPhone(phone);
        Users user = this.findUserByCondition(userQueryDbDTO);
        if(null != user){
            // 注册用户信息
            log.error("当前手机号已被绑定，请绑定其他手机号:{}",phone);
            throw new BusinessException(UserCodeEnum.PHONE_EXISTS_ERROR);
        }
        return this.getBaseMapper().update(Wrappers.lambdaUpdate(Users.class)
                .set(Users::getUserPhone,phone)
                .set(Users::getUserType,"user")
                .set(Users::getBindPhoneTime, LocalDateTime.now())
                .eq(Users::getId,userId)) > 0;
    }
}
